package com.hxl.olympic.fragment;

import android.os.Build;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.hxl.okhttp.response.JsonResponseHandler;
import com.hxl.olympic.R;
import com.hxl.olympic.util.App;
import com.hxl.olympic.util.Constant;
import com.hxl.olympic.util.DemoDataProvider;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.xuexiang.xui.widget.toast.XToast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;

public class CityWeatherFragment extends BaseFragment {
    @BindView(R.id.layout_refresh)
    SmartRefreshLayout layoutRefresh;

    String city;

    public CityWeatherFragment(String city) {
        this.city = city;
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void initialize() {
        //下拉刷新动画
        RefreshHeader header = getRefreshHeader(DemoDataProvider.Item.PhoenixHeader);
        layoutRefresh.setRefreshHeader(header);
        layoutRefresh.autoRefresh();

    }

    @Override
    public void initViews() {

    }


    @Override
    public void initData() {
        if (city.equals("北京")){
            //获取天气信息
            Map<String, String> params = new HashMap<>();//组合参数
            params.put("city",city);
            params.put("key", Constant.WEATHER_KEY);
            ((App)activity.getApplication()).getOkHttpUtils().post(Constant.WEATHER_URL, params, new JsonResponseHandler() {
                @Override
                public void onSuccess(int statusCode, JSONObject response) {
                    try {
                        if (response.getString("reason").equals("查询成功!")) {
                            XToast.success(activity, response.toString(), Toast.LENGTH_SHORT).show();
                        } else {
                            XToast.error(activity, response.getString("reason"), Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        XToast.success(activity, "查询失败", Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, String error_msg) {
                    XToast.error(activity, "网络请求失败!", Toast.LENGTH_SHORT).show();

                }
            });
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_city_weather;
    }
}
